/*---------------------------------------------------------------------
 * File name: ds18b20.h
 *
 * Copyright (c) <2020-2022>, <ChenLong>
 *
 * All rights reserved.
 *
 * Author: ChenLong
 * Email: worldlong@foxmail.com
 *--------------------------------------------------------------------*/
#pragma once
/*
*/
#include "hal_gpio.h"
#include "hal_timer.h"
/*
*/
#define DS18B20_CMD_READ_ROM         0x33
#define DS18B20_CMD_MATCH_ROM        0x55
#define DS18B20_CMD_SKIP_ROM         0xcc
#define DS18B20_CMD_CONVERT_T        0x44
#define DS18B20_CMD_READ_SCRATCHPAD  0xbe
#define DS18B20_CMD_WRITE_SCRATCHPAD 0x4e
#define TEMP_NONE       -30000
/*
*/
class DS18B20 
{
public:
  DS18B20(HAL_GPIO *dq_in, HAL_GPIO *dq_out, HAL_Timer *timer, bool dq_out_reverse) :
    online_flag(false),
    rom{0},
    _dq_in(dq_in),
    _dq_out(dq_out),
    _timer(timer),
    _dq_out_reverse(dq_out_reverse)
  {
  }
  bool online_flag;
  uint8_t rom[8];
  
  bool init();
  bool reset();
  void read_rom(uint8_t *buffer);
  void set_rom(uint8_t *buffer);
  void match_rom();
  void skip_rom();
  void read_scratchpad(uint8_t *buffer);
  void write_scratchpad(uint8_t *buffer);
  void start_convert(bool skip);
  void set_alarm(int8_t high, int8_t low);
  void set_bits(uint8_t bits);
  bool check();
  int16_t temperature();
  
private:
  HAL_GPIO *_dq_in;
  HAL_GPIO *_dq_out;
  HAL_Timer *_timer;
  bool _dq_out_reverse;
  
  
  void dq_out_high();
  void dq_out_low();
  void write(uint8_t *buffer, int number);
  void read(uint8_t *buffer, int number);
};
